package com.ruoyi.file.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.file.config.OssConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.function.ObjDoubleConsumer;

/**
 * 类名：
 * 作者：WF
 * 功能：阿里云文件上传
 */
@Service
@Primary
@Slf4j
public class OssSysFileServiceImpl implements ISysFileService{
	@Autowired
	private OSS ossClient;
	@Autowired
	private OssConfig ossConfig;
	@Override
	public String uploadFile(MultipartFile file,String module) throws Exception {
		// 得到bucketName名字
		String bucketName = ossConfig.getBucketName();
		// 最后生成的url地址的前缀
		String urlPrefix = "https://"  + bucketName + "." + ossConfig.getEndpoint();
		// 设置保存文件的格式
		String format = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
		// 定义文件名的前缀
		String prefix = UUID.randomUUID().toString().replace("-", "");
		// 得到原始的文件名
		String oldFileName = file.getOriginalFilename();
		// 得到原始文件名的后缀名
		String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
		// 最后得到完整的文件名
		String fileName = module + "/" + format + "/" + prefix + suffix;

		// 创建OSSClient实例（在OssConfig中定义）
		// OSS ossClient = new OSSClientBuilder().build(endpoint,"LTAI5tQVGe13nDLGAtntrF4Q","3BQ3IX3GWL9ZiS5r6D49LoF8uAmtWn");
		// OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccesskey(), ossConfig.getAccessSecret());
		try {
			// 创建PutObjectRequest对象。
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream());
			// 进行文件上传
			PutObjectResult result = ossClient.putObject(putObjectRequest);
			System.out.println("result = " + result);
		} catch (OSSException oe) {
			oe.printStackTrace();
		} finally {
			// if (ossClient != null) {
			// 	ossClient.shutdown();
			// }
		}
		String url = urlPrefix +  "/" + fileName;
		log.info("url:{}",url);
		return url;
	}
}
